<?php
$perms = $AppUI->acl();

require_once(DP_BASE_DIR."/modules/projects/items/projectitems.class.php");

$arr = xml2Array("/root", $_POST['xml']);
$results = array('success' => TRUE, 'messages' => array());
$updateIds = array();
$project_id = 0;
if (count($arr['item']) > 0) {
	if (!is_array($arr['item'][0])) {
		$tmp = $arr['item'];
		$arr['item'] = array($tmp);
	}
	$project_id = 0;
	foreach($arr['item'] as $data ) {
		$obj = new CMdProject_items();
		if (!$obj->bind($data)) {
			$results['success'] = FALSE;
			$results['messages'] []= $obj->_error . print_r($data, true);
			continue;
		}
		$project_id = $obj->pitem_project;
		if ($msg = $obj->store()) {
			$results['success'] = FALSE;
			$results['errors'] = $msg;
			continue;
		} else {
			$updateIds []= $obj->pitem_id;
		}
	}
	
	//delete other items:
	if (count($updateIds) > 0) {
		if ($project_id > 0) {
			$sql = "delete from project_items where pitem_project = $project_id and pitem_id not in (" . implode(', ', $updateIds) . ")";
			db_exec($sql);
		}
	}	
}

header('Content-Type: text/xml');

$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');

$xml->startElement('root');

$xml->writeElement('success', $results['success'] ? 'true' : 'false');
$xml->writeElement('errors', addslashes(htmlentities(implode('<br/>', $results['messages']))));
if (count($results['messages']) > 0) {
	$xml->writeElement('messages', addslashes(htmlentities(implode('<br/>', $results['messages']))));
}

$xml->endElement();

echo $xml->outputMemory(true);
?>